package com.gdwz.ps.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.CycleDetectionStrategy;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import xz.facade.user.model.Result;

import com.xzsoft.gdwz.ps.model.Fj;
import com.xzsoft.gdwz.ps.model.InqOrder;
import com.xzsoft.gdwz.ps.model.InqOrderLine;
import com.xzsoft.gdwz.ps.model.InqVendorHeader;
import com.xzsoft.gdwz.ps.model.InqVendorLine;
import com.xzsoft.gdwz.ps.model.psInqRsult;
import com.xzsoft.gdwz.services.InqOrderService;
import com.xzsoft.gdwz.services.InqVendorService;


/**
 * <p>Title: 远程评审</p>
 * <p>Description: </p>
 * <p>Company:兴竹信息 </p>
 * @author:杨   光
 * @date:2016-11-11 上午10:31:29
 */
@Controller
@RequestMapping("/review")
public class ReviewController {
	
	Logger logger = Logger.getLogger(ReviewController.class);
	
	@Autowired
	private InqOrderService inqOrderService;
	
	@Autowired
	private InqVendorService inqVendorService;

	/**
	 * 远程评审获取询价单
	 * @param request
	 * @param response
	 * @throws IOException
	 * void
	 */
	@RequestMapping("/getReviewMessage")
	public void getInqOrder(HttpServletRequest request,HttpServletResponse response) throws IOException {
		
		response.setCharacterEncoding("UTF-8");
	
			String createby = request.getParameter("createby");
			Result result = new Result();
			try {
				if(createby==null||"".equals(createby)){
					result.setResult("");
					result.setResultCode("C0001");
					result.setResultMessage("参数不能为空！");
					result.setSuccess(false);
					JSONObject jb = JSONObject.fromObject(result);
			    	response.getWriter().println(jb.toString());
					return ;
				}
				if(inqOrderService.getCreateby(createby)==null){
					result.setResult("");
					result.setResultCode("C0002");
					result.setResultMessage("createby参数不合法！");
					result.setSuccess(false);
					JSONObject jb = JSONObject.fromObject(result);
			    	response.getWriter().println(jb.toString());
					return ;
				}
				List<InqOrder> inqlist = new ArrayList<InqOrder>();	
				logger.info(inqlist.toString());
				inqlist = inqOrderService.getInqOrder(createby);
				if(inqlist.size()<1){
					result.setResult("");
					result.setResultCode("C0003");
					result.setResultMessage("无符合条件的询价单！");
					result.setSuccess(false);
					JSONObject jb = JSONObject.fromObject(result);
			    	response.getWriter().println(jb.toString());
					return ;
				}
				for(int i=0;i<inqlist.size();i++){
				    List<InqOrderLine> linelist = new ArrayList<InqOrderLine>();
				    List<InqVendorHeader> vendorHeaderlist = new ArrayList<InqVendorHeader>();
				    List<Fj> fjlist = new ArrayList<Fj>();
				    linelist = inqOrderService.getInqOrderLine(inqlist.get(i).getInqId());	
				    vendorHeaderlist = inqOrderService.getInqVendorHeader(inqlist.get(i).getInqId());
				    fjlist = inqOrderService.getFile(inqlist.get(i).getInqId());
				    //logger.info("供应商报价行信息"+vendorHeaderlist.toString());
				    InqOrder io = new InqOrder();
				    io.setInqId(inqlist.get(i).getInqId());
				    io.setInqCode(inqlist.get(i).getInqCode());
				    io.setInqName(inqlist.get(i).getInqName());
				    io.setInqType(inqlist.get(i).getInqType());
				    io.setDeliveryDate(inqlist.get(i).getDeliveryDate());
				    io.setInqEndDate(inqlist.get(i).getInqEndDate());
				    io.setCreateBy(inqlist.get(i).getCreateBy());
				    io.setCreateDate(inqlist.get(i).getCreateDate());
				    io.setVendorId(inqlist.get(i).getVendorId());
				    io.setPayWay(inqlist.get(i).getPayWay());
				    io.setCnyCode(inqlist.get(i).getCnyCode());
				    io.setInqDesc(inqlist.get(i).getInqDesc());
				    io.setInqStatus(inqlist.get(i).getInqStatus());
				    io.setTaxRate(inqlist.get(i).getInqStatus());
				    io.setTaxRate(inqlist.get(i).getTaxRate());
				    io.setIsYq(inqlist.get(i).getIsYq());
				    io.setBjCount(inqlist.get(i).getBjCount());
				    io.setLimitBj(inqlist.get(i).getLimitBj());
				    io.setPurContent(inqlist.get(i).getPurContent());
				    io.setPublishDate(inqlist.get(i).getPublishDate());
				    io.setReviewMethod(inqlist.get(i).getReviewMethod());
				    io.setLimitBjCount(inqlist.get(i).getLimitBjCount());
				    io.setYsZje(inqlist.get(i).getYsZje());
				    io.setComName(inqlist.get(i).getComName());
				    io.setPayRate(inqlist.get(i).getPayRate());
				    JsonConfig jsonConfig = new JsonConfig();
					jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
					JSONArray line = JSONArray.fromObject(linelist, jsonConfig);
					io.setOrderLine(line.toString());
					for(int j=0;j<vendorHeaderlist.size();j++)
					{
						InqVendorHeader iv = new InqVendorHeader();
						iv.setInqVendoHid(vendorHeaderlist.get(j).getInqVendoHid());
						iv.setInqId(vendorHeaderlist.get(j).getInqId());
						iv.setVendorId(vendorHeaderlist.get(j).getVendorId());
						iv.setVendorName(vendorHeaderlist.get(j).getVendorName());
						iv.setSumBjPrice(vendorHeaderlist.get(j).getSumBjPrice());						
						List<InqVendorLine> vendorLinelist = new ArrayList<InqVendorLine>();
						vendorLinelist = inqVendorService.getInqVendorLine(vendorHeaderlist.get(j).getInqVendoHid());
						JSONArray vendorLine = JSONArray.fromObject(vendorLinelist, jsonConfig);
						iv.setInqVendorLine(vendorLine.toString());
						List<Fj> filist = new ArrayList<Fj>();
						filist = inqOrderService.getVendorFile(vendorHeaderlist.get(j).getInqId(), vendorHeaderlist.get(j).getVendorId());
						List<Map<String, String>> list = new ArrayList<Map<String, String>>();
						for(int m=0;m<fjlist.size();m++){
							Map<String,String> map = new HashMap<String,String>();
							String url = "http://219.142.82.140:8090/gdxj/xipAttMrgAction.do?method=down&selectedIds="+fjlist.get(m).getAttId();
					    	map.put("bjurl", url);
					    	list.add(map);
						}
						JSONArray vendorfile = JSONArray.fromObject(list, jsonConfig);
						iv.setBjFile(vendorfile.toString());
						vendorHeaderlist.set(j, iv);
					}
					JSONArray vendorHeader = JSONArray.fromObject(vendorHeaderlist, jsonConfig);
				    io.setInqVendorHeader(vendorHeader.toString());
				    List<Map<String, String>> list = new ArrayList<Map<String, String>>();
				    for(int x=0;x<fjlist.size();x++){
				    	Map<String,String> map = new HashMap<String,String>();
				    	String url = "http://219.142.82.140:8090/gdxj/xipAttMrgAction.do?method=down&selectedIds="+fjlist.get(x).getAttId();
				    	map.put("url", url);
				    	map.put("classify", fjlist.get(x).getBusNo());
				    	list.add(map);
				    }
				    JSONArray listfile = JSONArray.fromObject(list, jsonConfig);
				    io.setAttachmentFile(listfile.toString());
				    inqlist.set(i, io);
				}
				JsonConfig jsonConfig = new JsonConfig();
				jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
				JSONArray json = JSONArray.fromObject(inqlist, jsonConfig);
				result.setResult(json.toString());
				result.setResultCode("");
				result.setResultMessage("");
				result.setSuccess(true);
				JSONObject jb = JSONObject.fromObject(result);
				response.getWriter().println(jb.toString());
				logger.info(jb.toString());
			} catch (IOException e1) {
				e1.printStackTrace();
			}finally{
				response.getWriter().flush();
				response.getWriter().close();
			}
		} 
	
	/**
	 * 远程评审更新询价单状态
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	@RequestMapping("/confirmReview")
	public void updateInqOrder(HttpServletRequest request,HttpServletResponse response) throws IOException{
		
		response.setCharacterEncoding("UTF-8");
		String inqId = request.getParameter("inqId");
		Result result = new Result();
		try {
			if(inqId==null||"".equals(inqId)){
				result.setResult("");
				result.setResultCode("C0001");
				result.setResultMessage("参数不能为空！");
				result.setSuccess(false);
				JSONObject jb = JSONObject.fromObject(result);
				response.getWriter().println(jb.toString());
				return ;
			}
			int res = inqOrderService.UpdateInqStatus(inqId);
			if(res>0){
				result.setResult("");
				result.setResultCode("C0004");
				result.setResultMessage("成功");
				result.setSuccess(true);
				JSONObject jb = JSONObject.fromObject(result);
				response.getWriter().println(jb.toString());
				return ;
			}else{
				result.setResult("");
				result.setResultCode("C0003");
				result.setResultMessage("参数不对");
				result.setSuccess(false);
				JSONObject jb = JSONObject.fromObject(result);
				response.getWriter().println(jb.toString());
				return ;
			}
		} catch (IOException e) {
			e.printStackTrace();
			result.setResult("");
			result.setResultCode("C0002");
			result.setResultMessage(e.getMessage());
			result.setSuccess(false);
			JSONObject jb = JSONObject.fromObject(result);
			response.getWriter().println(jb.toString());
			response.getWriter().flush();
			response.getWriter().close();
			return ;
		}finally{
			response.getWriter().flush();
			response.getWriter().close();
		}
	}	
	
	/**
	 * 远程评审接收评审结果
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	@RequestMapping("/reciveResult")
	public void reciveResult(HttpServletRequest request,HttpServletResponse response) throws IOException{
		
		response.setCharacterEncoding("UTF-8");
		String resultObj = request.getParameter("psResult");
		JSONObject obj = null;
		Result result = new Result();
		if(resultObj==null||"".equals(resultObj)){
			result.setResult("");
			result.setResultCode("C0013");
			result.setResultMessage("psResult参数不能为空！");
			result.setSuccess(false);
			JSONObject jb = JSONObject.fromObject(result);
			response.getWriter().println(jb.toString());
			response.getWriter().flush();
			response.getWriter().close();
			return;
		}
		try {
			obj = JSONObject.fromObject(resultObj);
		} catch (Exception e) {
			e.printStackTrace();
			result.setResult("");
			result.setResultCode("C0011");
			result.setResultMessage("psResult格式不正确！");
			result.setSuccess(false);
			JSONObject jb = JSONObject.fromObject(result);
			response.getWriter().println(jb.toString());
			response.getWriter().flush();
			response.getWriter().close();
			return;
		}
		/*
		 * 保存结果
		 * 处理附件
		 */
		try {
				logger.info("obj"+obj.toString());
				psInqRsult resultmap = new psInqRsult();
				//保存询价单信息
				resultmap.setInqId((String) obj.get("inqId"));
				resultmap.setbProposal((String) obj.get("bProposal")); //采购建议
				resultmap.setpOpinion((String) obj.get("pOpinion"));//配送中心意见
				resultmap.setPsExperts((String) obj.get("psExperts"));//评审专家
				resultmap.setOrgInqContent((String) obj.get("orgInqContent"));//中标理由
				inqOrderService.savePsResult(resultmap);
				//处理附件
				String psfjUrl = (String) obj.get("psfjUrl");
				JSONArray inqVendorHeader = (JSONArray) obj.get("inqVendorH");
				logger.info("inqVendorHeader"+inqVendorHeader.toString());
				for(int j=0;j<inqVendorHeader.size();j++){
				//保存询价单报价主信息	
					JSONObject objl = (JSONObject)inqVendorHeader.get(j);
					logger.info("objl"+objl.toString());
					psInqRsult map = new psInqRsult();
					map.setInqVendorHid((String) objl.get("inqVendorHid"));
					map.setRownum((String) objl.get("rownum"));
					map.setPsPrice((String) objl.get("psPrice"));
					double businessScore = (Double) objl.get("businessScore")/0.1;
					double technicalScore = (Double) objl.get("technicalScore")/0.4;
					double priceScore = (Double) objl.get("priceScore")/0.5;
					map.setBusinessScore(businessScore);
					map.setTechnicalScore(technicalScore);
					map.setPriceScore(priceScore);
				    map.setIsInvalid((String) objl.get("isInvalid"));
				    map.setSumScore((String) objl.get("sumScore"));
				    map.setSwdx((String) objl.get("swdx"));
				    map.setJsdx((String) objl.get("jsdx"));
				    inqOrderService.saveInqVendorh(map);
				    inqOrderService.saveInqVendorl(map);
				}
		} catch (Exception e) {
			e.printStackTrace();
			e.printStackTrace();
			result.setResult("");
			result.setResultCode("C0014");
			result.setResultMessage(e.getMessage());
			result.setSuccess(false);
			JSONObject jb = JSONObject.fromObject(result);
			response.getWriter().println(jb.toString());
			response.getWriter().flush();
			response.getWriter().close();
			return ;
		}
		/*
		 * 返回正确的结果集
		 */
		result.setResult("");
		result.setResultCode("");
		result.setResultMessage("");
		result.setSuccess(true);
		JSONObject jb = JSONObject.fromObject(result);
		response.getWriter().println(jb.toString());
		response.getWriter().flush();
		response.getWriter().close();
	}
	
}














